﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using com.huigo.Framework.Passport;
using com.huigo.Framework.ServiceUtils;

namespace com.huigo.Admin.Web
{
    public partial class hx : System.Web.UI.Page
    {
        protected string operType = string.Empty;
        protected string response = string.Empty;
        protected bool IsLogin = true;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(f("oper")))
            {
                operType = f("oper");
            }
            else
            {
                operType = q("oper");
            }

            #region 参数选择
            if (operType != "userLogin" && !UserPassport.ChkCookieLogin())
            {
                response = "invalidOrNull";
            }
            switch (operType)
            {
                case "userLogin":
                    UserLogin();
                    break;
                case "orderflow":
                    GetOrderFlow();
                    break;
                case"policyflow":
                    GetPolicyFlow();
                    break;
                case "CheckInvoiceOrder":
                   response= CheckInvoiceOrder();
                    break;
                case "NoCheckInvoiceOrder":
                  response=  NoCheckInvoiceOrder();
                    break;
                case "DeliverInvoiceOrder":
                   response= DeliverInvoiceOrder();
                    break;
                case "GetInvoiceOrderFlowList":
                    GetInvoiceOrderFlowList();
                    break;
                case "GetOrderAddress":
                    GetOrderAddress();
                    break;
                case "checkCustName":
                   response= checkCustName();
                    break;
                case"GetLoginLog":
                    GetLoginLog();
                    break;
                case"GetSales":
                    GetSales();
                    break;
                case"GetSalesDetail":
                    GetSalesDetail();
                    break;
            }

            #endregion

            Response.Write(response);
            Response.End();

        }
        public string RequestString(string name)
        {
            string v = Request[name];
            if (v == null)
            {
                v = string.Empty;
            }
            v = v.Replace("<", "&lt;");
            v = v.Replace(">", "&gt;");
            return v.Trim();
        }
        private void UserLogin()
        {
            string username = f("username");
            string password = f("pwd");
            string validcode = f("identitycode");
            HttpCookie cookie = Request.Cookies["vvvvalidccccode"];
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                response = "-1";
                return;
            }
            if (cookie == null || cookie.Value != validcode)
            {
                response = "-2";
                return;
            }
            if (UserPassport.Login(username, password, 360))
            {
                response = "1";
            }
            else
            {
                response = "-1";
            }
        }

        private void GetOrderFlow()
        {
            string resultFormat = @"{{""msg"":""{0}"",""data"":[{1}]}}";
            string result = string.Empty;
            string dataFormat = @"{{""oper"":""{0}"",""time"":""{1}"",""status"":""{2}"",""memo"":""{3}""}}";

            string oid = q("oid");
            if (!string.IsNullOrEmpty(oid))
            {
                List<RequestFuncParams> requestList = new List<RequestFuncParams>();
                requestList.Add(new RequestFuncParams("orderFid", oid.ToString()));
                BaseService service = new BaseService();
                ParserXml parserXml = service.RequestEntryService(Dict.ERequestFunc.GET_ORDER_FLOW_LIST, requestList);
                if (parserXml.RowsCount > 0)
                {
                    List<string> dataList = new List<string>();
                    for (int i = 0; i < parserXml.RowsCount; i++)
                    {
                        dataList.Add(string.Format(dataFormat, parserXml["UserName", i].ToString() == string.Empty ? "服务器" : parserXml["UserName", i].ToString(), parserXml["FlowCreatedOn", i].ToString().Replace("T", "  "), parserXml["StatusMeno", i].ToString(), parserXml["FlowMemo", i].ToString()));
                    }

                    result = string.Format(resultFormat, "suc", string.Join(",", dataList.ToArray()));
                }
                else
                {
                    result = string.Format(resultFormat, "err", "");
                }
            }
            else
            {
                result = string.Format(resultFormat, "err", "");
            }
            response = result;
        }
        //查询保单操作流
        private void GetPolicyFlow()
        {
            string resultFormat = @"{{""msg"":""{0}"",""data"":[{1}]}}";
            string result = string.Empty;
            string dataFormat = @"{{""oper"":""{0}"",""time"":""{1}"",""status"":""{2}"",""memo"":""{3}""}}";

            string pid = q("pid");
            if (!string.IsNullOrEmpty(pid))
            {
                List<RequestFuncParams> requestList = new List<RequestFuncParams>();
                requestList.Add(new RequestFuncParams("policyFid", pid.ToString()));
                BaseService service = new BaseService();
                ParserXml parserXml = service.RequestEntryService(Dict.ERequestFunc.GET_POLICY_FLOW_LIST, requestList);
                if (parserXml.RowsCount > 0)
                {
                    List<string> dataList = new List<string>();
                    for (int i = 0; i < parserXml.RowsCount; i++)
                    {
                        dataList.Add(string.Format(dataFormat, parserXml["UserName", i].ToString() == string.Empty ? "服务器" : parserXml["UserName", i].ToString(), parserXml["FlowCreatedOn", i].ToString().Replace("T", "  "), parserXml["StatusMeno", i].ToString(), parserXml["FlowMemo", i].ToString()));
                    }

                    result = string.Format(resultFormat, "suc", string.Join(",", dataList.ToArray()));
                }
                else
                {
                    result = string.Format(resultFormat, "err", "");
                }
            }
            else
            {
                result = string.Format(resultFormat, "err", "");
            }
            response = result;
        }
        //发票订单操作流
        private void GetInvoiceOrderFlowList()
        {
            string resultFormat = @"{{""msg"":""{0}"",""data"":[{1}]}}";
            string result = string.Empty;
            string dataFormat = @"{{""oper"":""{0}"",""time"":""{1}"",""status"":""{2}"",""memo"":""{3}""}}";

            string orderFid = q("orderFid");
            if (!string.IsNullOrEmpty(orderFid))
            {
                List<RequestFuncParams> requestList = new List<RequestFuncParams>();
                requestList.Add(new RequestFuncParams("orderFid", orderFid.ToString()));
                BaseService service = new BaseService();
                ParserXml parserXml = service.RequestEntryService(Dict.ERequestFunc.GET_INVOICE_ORDER_FLOW_LIST, requestList);
                if (parserXml.RowsCount > 0)
                {
                    List<string> dataList = new List<string>();
                    for (int i = 0; i < parserXml.RowsCount; i++)
                    {
                        dataList.Add(string.Format(dataFormat, parserXml["UserName", i].ToString() == string.Empty ? "服务器" : parserXml["UserName", i].ToString(), parserXml["FlowCreatedOn", i].ToString().Replace("T", "  "), parserXml["StatusMeno", i].ToString(), parserXml["FlowMemo", i].ToString()));
                    }

                    result = string.Format(resultFormat, "suc", string.Join(",", dataList.ToArray()));
                }
                else
                {
                    result = string.Format(resultFormat, "err", "");
                }
            }
            else
            {
                result = string.Format(resultFormat, "err", "");
            }
            response = result;
        }
        
        //发票订单审核通过
        private string CheckInvoiceOrder()
        {
            string resultFormat = @"{{""msg"":""{0}""}}";
            string msg = string.Empty;
            string orderId = q("orderId"); ;
            if (UserId > 0)
            {
                List<RequestFuncParams> arglist = new List<RequestFuncParams>();
                arglist.Add(new RequestFuncParams("invoiceOrderID", orderId));
                BaseService bs = new BaseService();
                ParserXml xml = bs.RequestEntryService(Dict.ERequestFunc.GET_INVOICE_ORDER_BY_ID, arglist);
                if (xml != null && xml.RowsCount > 0)
                {
                    int status = Convert.ToInt32(xml["OrderStatusFid", 0]);
                    if (status == (int)Dict.InvoiceStatus.UnCheck || status == (int)Dict.InvoiceStatus.CheckFail)
                    {
                        List<RequestFuncParams> list = new List<RequestFuncParams>();
                        list.Add(new RequestFuncParams("invoiceOrderID", orderId));
                        list.Add(new RequestFuncParams("status", ((int)Dict.UpdateInvoiceOrderStatus.CheckOK).ToString()));
                        list.Add(new RequestFuncParams("userID", UserId.ToString()));
                        list.Add(new RequestFuncParams("Meno", ""));
                        list.Add(new RequestFuncParams("Fedex", ""));
                        list.Add(new RequestFuncParams("FedexComPany", ""));
                        BaseService service = new BaseService();
                        ParserXml parser = service.RequestEntryService(Dict.ERequestFunc.UPDATE_INVOICE_ORDER, list);
                        if (parser != null && parser.RowsCount > 0 && parser["returnargs", 0] == "true")
                        {
                            msg = "suc";
                        }
                        else
                        {
                            msg = "err";
                        }
                    }
                    else
                    {
                        msg = "err";
                    }
                }
                else
                {
                    msg = "err";
                }
            }
           
            return string.Format(resultFormat, msg);
        }
        //发票订单审核不通过
        private string NoCheckInvoiceOrder()
        {
            string resultFormat = @"{{""msg"":""{0}""}}";
            string msg = string.Empty;
            string orderId = q("orderId");
            string Meno = RequestString("meno");
            if (UserId > 0)
            {
                List<RequestFuncParams> arglist = new List<RequestFuncParams>();
                arglist.Add(new RequestFuncParams("invoiceOrderID", orderId));
                BaseService bs = new BaseService();
                ParserXml xml = bs.RequestEntryService(Dict.ERequestFunc.GET_INVOICE_ORDER_BY_ID, arglist);
                if (xml != null && xml.RowsCount > 0)
                {
                    int status = Convert.ToInt32(xml["OrderStatusFid", 0]);
                    switch (status)
                    {
                        case (int)Dict.InvoiceStatus.UnCheck:
                            List<RequestFuncParams> list = new List<RequestFuncParams>();
                            list.Add(new RequestFuncParams("invoiceOrderID", orderId));
                            list.Add(new RequestFuncParams("status", ((int)Dict.UpdateInvoiceOrderStatus.CheckFail).ToString()));
                            list.Add(new RequestFuncParams("userID", UserId.ToString()));
                            list.Add(new RequestFuncParams("Meno", Meno));
                            list.Add(new RequestFuncParams("Fedex", ""));
                            list.Add(new RequestFuncParams("FedexComPany", ""));
                            BaseService service = new BaseService();
                            ParserXml parser = service.RequestEntryService(Dict.ERequestFunc.UPDATE_INVOICE_ORDER, list);
                            if (parser != null && parser.RowsCount > 0 && parser["returnargs", 0] == "true")
                            {
                                msg = "suc";
                            }
                            else
                            {
                                msg = "err";
                            }
                            break;
                        default:
                            break;
                    }
                }
                else
                {
                    msg = "err";
                }
            }
            return string.Format(resultFormat, msg);
        }
        //配送
        private string DeliverInvoiceOrder()
        {
            string resultFormat = @"{{""msg"":""{0}""}}";
            string msg = string.Empty;
            string orderId = q("orderId");
            string Fedex = RequestString("Fedex");
            string FedexComPany = RequestString("FedexComPany");
            if (UserId > 0)
            {
                List<RequestFuncParams> arglist = new List<RequestFuncParams>();
                arglist.Add(new RequestFuncParams("invoiceOrderID", orderId));
                BaseService bs = new BaseService();
                ParserXml xml = bs.RequestEntryService(Dict.ERequestFunc.GET_INVOICE_ORDER_BY_ID, arglist);
                if (xml != null && xml.RowsCount > 0)
                {
                    int status = Convert.ToInt32(xml["OrderStatusFid", 0]);
                    if (status == (int)Dict.InvoiceStatus.CheckSuc)
                    {
                        List<RequestFuncParams> list = new List<RequestFuncParams>();
                        list.Add(new RequestFuncParams("invoiceOrderID", orderId));
                        list.Add(new RequestFuncParams("status", ((int)Dict.UpdateInvoiceOrderStatus.DeliverSuc).ToString()));
                        list.Add(new RequestFuncParams("userID", UserId.ToString()));
                        list.Add(new RequestFuncParams("Meno", ""));
                        list.Add(new RequestFuncParams("Fedex", Fedex));
                        list.Add(new RequestFuncParams("FedexComPany", FedexComPany));
                        BaseService service = new BaseService();
                        ParserXml parser = service.RequestEntryService(Dict.ERequestFunc.UPDATE_INVOICE_ORDER, list);
                        if (parser != null && parser.RowsCount > 0 && parser["returnargs", 0] == "true")
                        {
                            msg = "suc";
                        }
                        else
                        {
                            msg = "err";
                        }
                    }
                    else
                    {
                        msg = "err";
                    }
                }
                else
                {
                    msg = "err";
                }
            }
            return string.Format(resultFormat, msg);
        }
        /// <summary>
        /// 查询配送地址
        /// </summary>
        private void GetOrderAddress()
        {
            string resultFormat = @"{{""msg"":""{0}"",""data"":[{1}]}}";
            string result = string.Empty;
            string dataFormat = @"{{""province"":""{0}"",""city"":""{1}"",""address"":""{2}"",""contact"":""{3}"",""tel"":""{4}""}}";

            string orderId = q("oid");
            if (!string.IsNullOrEmpty(orderId))
            {
                List<RequestFuncParams> list = new List<RequestFuncParams>();
                list.Add(new RequestFuncParams("invoiceOrderID", orderId));
                BaseService service = new BaseService();
                ParserXml parser = service.RequestEntryService(Dict.ERequestFunc.GET_INVOICE_ORDER_BY_ID, list);
                List<string> dataList = new List<string>();
                if (parser != null && parser.RowsCount > 0)
                {
                    dataList.Add(string.Format(dataFormat, parser["OrderProvince", 0], parser["OrderCity", 0], parser["OrderAddress", 0], parser["OrderContact", 0], parser["OrderTel", 0]));
                    result = string.Format(resultFormat, "suc", string.Join(",", dataList.ToArray()));
                }
            }
            else
            {
                result = string.Format(resultFormat, "err", "");
            }
            response = result;
        }

        private string checkCustName()
        {
            string resultFormat = @"{{""msg"":""{0}"",""price"":""{1}""}}";
            string custName = RequestString("custName");
            string msg = string.Empty;
            string price = "";
            List<RequestFuncParams> argList = new List<RequestFuncParams>();
            argList.Add(new RequestFuncParams("userName", custName));
            BaseService baseService = new BaseService();
            ParserXml parser = baseService.RequestEntryService(Dict.ERequestFunc.CHECK_USER_NAME, argList);

            if (parser != null && parser.RowsCount > 0)
            {
                msg = "suc";
                price = ConvertCurrencyPay(Convert.ToDecimal(parser["CustTotalFee", 0])).ToString();
            }
            else
            {
                msg = "err";
            }
            return string.Format(resultFormat, msg, price);
        }
        /// <summary>
        /// 查询登录日志
        /// </summary>
        private void GetLoginLog()
        {
            string custFid = RequestString("custId");
            string resultFormat = @"{{""msg"":""{0}"",""data"":[{1}]}}";
            string result = string.Empty;
            string dataFormat = @"{{""time"":""{0}"",""ip"":""{1}""}}";
            if (UserId > 0)
            {
                List<RequestFuncParams> list = new List<RequestFuncParams>();
                list.Add(new RequestFuncParams("createBy", custFid));
                list.Add(new RequestFuncParams("type", "1"));
                BaseService service = new BaseService();
                ParserXml parser = service.RequestEntryService(Dict.ERequestFunc.GET_LOGIN_LOG, list);
                List<string> dataList = new List<string>();
                if (parser != null && parser.RowsCount > 0)
                {
                    for (int i = 0; i < parser.RowsCount; i++)
                    {
                        dataList.Add(string.Format(dataFormat, parser["LogCreatedOn", i], parser["LogIp", i]));
                        result = string.Format(resultFormat, "suc", string.Join(",", dataList.ToArray()));
                    }
                }
            }
            response = result;
        }
        //统计经销商
        private void GetSales()
        {
            string fromDate = RequestString("start");
            string toDate = RequestString("end");
            string custId = RequestString("custFid");
            string resultFormat = @"{{""msg"":""{0}"",""data"":[{1}]}}";
            string result = string.Empty;
            string dataFormat = @"{{""orderNo"":""{0}"",""product"":""{1}"",""policyNo"":""{2}"",""price"":""{3}"",""orderTime"":""{4}""}}";
            List<RequestFuncParams> list = new List<RequestFuncParams>();
            list.Add(new RequestFuncParams("start", fromDate));
            list.Add(new RequestFuncParams("end", toDate));
            list.Add(new RequestFuncParams("userId", UserId.ToString()));
            list.Add(new RequestFuncParams("custFid", custId));
            BaseService service = new BaseService();
            ParserXml parser = service.RequestEntryService(Dict.ERequestFunc.GET_SALES_DETAIL, list);
            List<string> dataList = new List<string>();
            if (parser != null && parser.RowsCount > 0)
            {
                for (int i = 0; i < parser.RowsCount; i++)
                {
                    dataList.Add(string.Format(dataFormat, parser["OrderNo", i], parser["OrderProductName", i], parser["PolicyNo", i], string.Format("{0:C2}", Convert.ToDecimal(parser["Price", i])), Convert.ToDateTime(parser["OrderPaidOn", i]).ToString("yyyy-MM-dd HH:mm")));
                    result = string.Format(resultFormat, "suc", string.Join(",", dataList.ToArray()));
                }
            }
            response = result;
        }
        private void GetSalesDetail()
        {
            string fromDate = RequestString("start");
            string toDate = RequestString("end");
            string product = RequestString("product");
            string userId = RequestString("user");
            string resultFormat = @"{{""msg"":""{0}"",""data"":[{1}]}}";
            string result = string.Empty;
            string dataFormat = @"{{""orderNo"":""{0}"",""product"":""{1}"",""policyNo"":""{2}"",""price"":""{3}"",""orderTime"":""{4}""}}";
            List<RequestFuncParams> list = new List<RequestFuncParams>();
            list.Add(new RequestFuncParams("start", fromDate));
            list.Add(new RequestFuncParams("end", toDate));
            list.Add(new RequestFuncParams("userId", userId));
            list.Add(new RequestFuncParams("productName", product));
            BaseService service = new BaseService();
            ParserXml parser = service.RequestEntryService(Dict.ERequestFunc.GET_TOTAL_SALES_DETAIL, list);
            List<string> dataList = new List<string>();
            if (parser != null && parser.RowsCount > 0)
            {
                for (int i = 0; i < parser.RowsCount; i++)
                {
                    dataList.Add(string.Format(dataFormat, parser["OrderNo", i], parser["OrderProductName", i], parser["PolicyNo", i], string.Format("{0:C2}", Convert.ToDecimal(parser["Price", i])), Convert.ToDateTime(parser["OrderPaidOn", i]).ToString("yyyy-MM-dd HH:mm")));
                    result = string.Format(resultFormat, "suc", string.Join(",", dataList.ToArray()));
                }
            }
            response = result;
        }
        //获取querystring
        public string q(string s)
        {
            if (Request.QueryString[s] != null)
            {
                return Server.UrlEncode(Request.QueryString[s]);
            }
            return string.Empty;
        }
        //获取post得到的参数
        protected string f(string s)
        {
            if (Request.Form[s] == null) return string.Empty;
            return Request.Form[s];
        }
        public decimal ConvertCurrencyPay(decimal currency)
        {
            /*舍分处理
            float f = (float)System.Math.Floor(currency);
            float d = currency - f;
            if (d.ToString().Length > 2)
            {
                return f+float.Parse(d.ToString().Substring(0, 3));
            }
            return currency;
            */
            decimal concurrency = (decimal)Math.Round(currency, 2);
            decimal thridCurrency = (decimal)Math.Round(currency, 3);
            if (concurrency - thridCurrency < 0)
            {
                concurrency = concurrency + 0.01M;
            }
            return (decimal)Math.Round(concurrency, 2);
        }
        private string JsonCharFilter(string sourceStr)
        {
            sourceStr = sourceStr.Replace("\\", "\\\\");
            sourceStr = sourceStr.Replace("\b", "\\\b");
            sourceStr = sourceStr.Replace("\t", "\\\t");
            sourceStr = sourceStr.Replace("\n", "\\\n");
            sourceStr = sourceStr.Replace("\n", "\\\n");
            sourceStr = sourceStr.Replace("\f", "\\\f");
            sourceStr = sourceStr.Replace("\r", "\\\r");
            return sourceStr.Replace("\"", "\\\"");
        }

        private long UserId
        {
            get
            {
                return UserPassport.GetCookieUserId();
            }
        }


    }
}
